package com.shanshan.wheel.rpc.common.registry;

import com.shanshan.wheel.rpc.common.exception.RpcErrorMessage;
import com.shanshan.wheel.rpc.common.exception.RpcException;
import com.shanshan.wheel.rpc.common.loadbalance.LoadBalance;
import com.shanshan.wheel.rpc.common.registry.util.CuratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @Description zk 服务发现实现类
 * @ClassName ZkServiceDiscovery
 * @Author 山山大魔王
 * @Date 2022/9/4 11:35
 * @Version 1.0
 */
@Component
@Slf4j
public class ZkServiceDiscovery implements ServiceDiscovery{

    @Autowired
    private LoadBalance loadBalance; // 负载均衡策略

    @Override
    public InetSocketAddress lookupService(String rpcServiceName) {
        CuratorFramework client = CuratorUtil.getClient();

        List<String> serviceAddressList = CuratorUtil.getServiceAddress(client, rpcServiceName);

        if(serviceAddressList == null || serviceAddressList.size() == 0){
            throw new RpcException(RpcErrorMessage.SERVICE_CAN_NOT_BE_FOUND, rpcServiceName);
        }
        // 通过负载均衡策略选择一个地址
        String targetServiceAddress = loadBalance.selectServiceAddress(serviceAddressList, rpcServiceName);
        log.info("成功找到服务地址:[{}]",targetServiceAddress);
        String[] split = targetServiceAddress.split(":");
        String host = split[0];
        Integer port = Integer.parseInt(split[1]);
        return new InetSocketAddress(host, port);
    }
}
